package xyz.syyrjx.blog.util.site;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import xyz.syyrjx.blog.entity.site.BingUrlRequest;

import java.util.List;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2024/2/25 13:26
 * @description ...
 * @since v0.0.1
 */
public class BingSubmitUtil {

    private static final Logger logger = LoggerFactory.getLogger(BingSubmitUtil.class);
    public static String endpoint;

    private static RestTemplate restTemplate;

    static {
        // restTemplate初始化、拦截器设置
        BingSubmitUtil.restTemplate = new RestTemplate();
        BingSubmitUtil.restTemplate.getInterceptors().add((request, body, execution) -> {
            HttpHeaders headers = request.getHeaders();
            headers.add("Host", "ssl.bing.com");
            headers.add("Content-Type", "application/json");
            return execution.execute(request,body);
        });
    }

    public static void submit(List<String> urlList) {
        try {
            logger.debug("{}", urlList);
            if (endpoint == null || endpoint.length() == 0) {
                logger.info("Bing提交失败，endpoint为空");
                return;
            }
            BingUrlRequest bingUrlRequest = new BingUrlRequest(urlList);
            logger.info("Bing提交开始:{}", bingUrlRequest);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(endpoint, bingUrlRequest, String.class);
            logger.info("Bing提交结果：{}", stringResponseEntity.getBody());
        }catch (Exception e) {
            logger.error("Bing提交失败：{}", e.getMessage());
            throw e;
        }
    }
}
